<?php
declare (strict_types = 1);

namespace app\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Argument;
use think\console\input\Option;
use think\console\Output;
use think\facade\Db;
use \app\common\Time;
use PDO;

class Order extends Command
{
  public $date = '';
  protected function configure()
  {
      // 指令配置
    $this->setName('order')
        ->addArgument('mothod', Argument::OPTIONAL, "your mothod")
        ->addOption('date', null, Option::VALUE_REQUIRED, '')
        ->setDescription('sync order');   
  }

  protected function execute(Input $input, Output $output)
  {
    if ($input->hasOption('date')) {
      $this->date = $input->getOption('date');
    } else {
      $this->date = '';
    }
    $mothod = trim($input->getArgument('mothod'));
    if (method_exists($this, $mothod)) {
      $this->$mothod();
    }else{
      $output->writeln("方法" . $mothod . '不存在' );
    }
  }
  //拉取美团订单
  public function meituan($stime = '')
  {
    if (!$stime) {
      list($stime,$etime) = Time::yesterday();

      // print_r($this->date);return;

      if ($this->date == 'today') {
        list($stime,$etime) = Time::today();
      }elseif ($this->date == 'yesterday') {
        list($stime,$etime) = Time::yesterday();
      }elseif ($this->date == 'week') {
        list($stime,$etime) = Time::week();
      }elseif ($this->date == 'lastWeek') {
        list($stime,$etime) = Time::lastWeek();
      }elseif ($this->date == 'month') {
        list($stime,$etime) = Time::month();
      }elseif ($this->date == 'lastMonth') {
        list($stime,$etime) = Time::lastMonth();
      }elseif ($this->date) {
        $this->date = str_replace('_',' ',$this->date);
        // print_r($this->date);return;
        $stime = strtotime($this->date);
      }else{
        $stime = time() - 300;
      }
    }

    

    $et = $stime + 120;
    echo date('Y-m-d H:i',$stime)."\n";
    if ($et > time()) {
      $et = time();
    }

    // print_r($stime);
    // return;

    $waimai = new \app\common\Waimai();
    $query['start_time'] = $stime;
    $query['end_time'] = $et;

    // $query['start_time'] = strtotime('2020-09-13 16:30:00');
    // $query['end_time'] = strtotime('2020-09-13 16:50:00');

    $query['page_size'] = 50;
    $res = $waimai->ddx_get('waimai/meituan_orders',$query);
    if (isset($res['data'])) {
      foreach ($res['data'] as $k) {
        $this->insertMeituan($k);
      }
    }
    if ($et < time()) {
      // print_r($et);
      $this->meituan($et);
    }
    // print_r($res);
  }

  //美团 订单入库
  private function insertMeituan($order){
    $vo = array();
    $order_sn = $order['orderid'] ;
    $sid = $order['sid'] ;
    $status = $order['status'] ;
    if ($status == 8) $status = 3;
    if ($status == 9) $status = -1;

    $squery = str_replace("Z",'=',$sid);
    parse_str($squery,$query);
    if (isset($query['uid'])) 
      $uid = $query['uid'];
    else
      $uid = $sid;
    
    $ck = Db::name('order')->where('order_sn',$order_sn)->find();
    if ($ck ) {
      if ($ck['status'] != $status) {
        Db::name('order')->where('order_sn',$order_sn)->update([
          'status'=>$status,
          'utime'=>time(),
          'uid'=>$uid,
        ]);
      }
      print_r($ck);
      return;
    }

    
    

    if ($uid) $vo['uid'] = $uid;
    // print_r($order);
    $vo['order_sn'] = $order_sn ;
    $vo['goods_name'] = $order['smstitle'] ;
    // $vo['goods_img'] = "http:".$order['item_img'] ;
    $vo['goods_price'] = $order['payprice'] ;
    $vo['goods_num'] = 1;
    $vo['source'] = 'meituan' ;
    $vo['pay_time'] = $order['paytime'] ;
    $vo['pay_price'] = $order['payprice'] ;
    $vo['commission_rate'] = 6;
    $vo['commission_price'] = $order['profit'] ;
    // $vo['earning_time'] = $order['refundtime'];
    $vo['ctime'] = strtotime($order['create_time']) ;
    $vo['utime'] = time() ;
    $vo['status'] = $status ;
    // print_r($vo);
    Db::name('order')->insert($vo);
  }

  //拉取饿了么订单
  public function ele($stime = '')
  {

    if (!$stime) {
      list($stime,$etime) = Time::yesterday();

      if ($this->date == 'today') {
        list($stime,$etime) = Time::today();
      }elseif ($this->date == 'yesterday') {
        list($stime,$etime) = Time::yesterday();
      }elseif ($this->date == 'week') {
        list($stime,$etime) = Time::week();
      }elseif ($this->date == 'lastWeek') {
        list($stime,$etime) = Time::lastWeek();
      }elseif ($this->date == 'month') {
        list($stime,$etime) = Time::month();
      }elseif ($this->date == 'lastMonth') {
        list($stime,$etime) = Time::lastMonth();
      }elseif ($this->date) {
        $this->date = str_replace('_',' ',$this->date);
        // print_r($this->date);return;
        $stime = strtotime($this->date);
      }else{
        $stime = time() - 300;
      }
    }
    //[pub_id] => 848420036
    // [pub_id] => 848420036
    $et = $stime + 300;
    if ($et > time()) {
      $et = time();
    }

    echo date('Y-m-d H:i',$stime).PHP_EOL;

    $tb = new \app\common\TaobaoApi();
    $r = $tb->get('taobao.tbk.order.details.get',[
      'start_time'=>toDatetime($stime),
      'end_time'=>toDatetime($et),
      'order_scene'=>2
      // 'start_time'=>'2020-09-03 11:10:00',
      // 'end_time'=>'2020-09-03 11:20:00',
    ]);
    print_r($r);
    $data = $r['tbk_order_details_get_response']['data']['results'];
    if (isset($data['publisher_order_dto'])) {
      $rows = $data['publisher_order_dto'];
      foreach ($rows as $order) {
          print_r($order);
        if ($order['order_type'] == '饿了么') {
          $this->insertEle($order);
          // print_r($order['order_type']);
        }
      }
    }

    // $r = $tb->get('taobao.tbk.activity.info.get',[
    //   'activity_material_id'=>'1579491209717',
    //   'adzone_id'=>'1971666093',
    // ]);
    if ($et < time()) {
      // print_r($et);
      // $this->ele($et);
    }

  }

  //饿了么 订单入库
  private function insertEle($order){
    $vo = array();
    $order_sn = $order['trade_parent_id'] ;
    $status = $order['tk_status'] ;
    $relation_id = $order['relation_id'] ;
    $user = Db::name('user')->where('relation_id',$relation_id)->find();
    $uid = 0;
    if ($user) $uid = $user['id'];
    $vo['uid'] = $uid;
    $vo['relation_id'] = $relation_id;
    
    // $ck = Db::name('order')->where('order_sn',$order_sn)->find();
    // if ($ck) return;

    $ck = Db::name('order')->where('order_sn',$order_sn)->find();
    if ($ck ) {
      if ($ck['status'] != $status) {
        Db::name('order')->where('order_sn',$order_sn)->update([
          'status'=>$status,
          'utime'=>time(),
          'uid'=>$uid,
        ]);
      }
      print_r($ck);
      return;
    }
    


    // print_r($order);
    $vo['order_sn'] = $order_sn ;
    $vo['goods_name'] = $order['item_title'] ;
    $vo['goods_img'] = "http:".$order['item_img'] ;
    $vo['goods_price'] = $order['alipay_total_price'] ;
    $vo['goods_num'] = $order['item_num'] ;
    $vo['source'] = 'ele' ;
    $vo['pay_time'] = strtotime($order['tk_paid_time'] );
    $vo['pay_price'] = $order['alipay_total_price'] ;
    $vo['commission_rate'] = $order['tk_total_rate'] ;
    $vo['commission_price'] = $order['pub_share_fee'] ;
    if (isset($order['tk_earning_time'])) {
      $vo['earning_time'] = strtotime($order['tk_earning_time']) ;
    }
    $vo['ctime'] = strtotime($order['tk_create_time']) ;
    $vo['utime'] = time() ;
    $vo['status'] = $status ;
    Db::name('order')->insert($vo);
  }

  //订单奖金分配
  function reward(){
    $reward = new \app\common\Reward();
    $list = Db::name('order')
              ->where('reward',0)
              ->page(1,50)
              ->order('id desc')
              ->select()->toArray();
    foreach ($list as $k) {
      $reward->run($k);
    }
  }

}
